//点击表单外就关闭表单
$(() => {
    //使body的minWidth和浏览器高度一致
    $(document.body).css('minHeight', window.innerHeight);
    //点击body使显示的表单消失
    $(document.body).on('click', function (e) {
        //点击的不是表单本身
        if ($(e.target).parents('.form-box').length === 0
            && !$(e.target).hasClass('form-box')
            //忽略alert的关闭
            && $(e.target).parents('.tip-alert').length === 0
            //忽略所有按钮的点击
            && e.target.tagName !== 'BUTTON') {
            let form = $('.form-area .show');
            if (form.length >= 1) {
                if (form.length == 2) form = form.eq(1);
                form.removeClass(form.attr('class').split(' ')[2] + '-slide-down show')
                    .addClass('fade-out');

                setTimeout(() => {
                    form.addClass('hide');
                }, 500);
                $('.sale .order-detail').html('');
            }
        }
    });
});

let DATA = {};
$(() => {
    let server = 'http://www.fjemiot.cn/erp/',
        max = 10000;
    $.ajax({
        url: server + 'employees',
        data: 'pageNum=1&pageSize=' + max,
        success: (reply) => {
            let {...e} = reply;
            DATA['employee'] = e['employees'];
            $(document.body).append(datalistgen('employee-list', reply['employees']));
        },
        error: (reply) => {
            console.log(reply);
        }
    });
    let saleList = $('.sale-list-contain');
    $.ajax({
        url: server + 'orderMaster',
        data: 'pageNum=1&pageSize=' + max,
        success: (reply) => {
            let {...o} = reply;
            let array = [];
            DATA['orderMaster'] = o['value'];
            for (let order of reply['value']) {
                order['name'] = order['customerNo'] + '-' + order['employeeNo'];
                order['employee'] = order['employeeNo'];
                order['customer'] = order['customerNo'];
                delete order['customerNo'];
                delete order['employeeNo'];
                if (order['state'] != 0) array.push(order);
            }
            saleList.html(datalistgen('sale-list', array));
        }
    });
    let returnList = $('.return-list-contain');
    $.ajax({
        url: server+'returnMaster',
        data: 'type=1&pageNum=1&pageSize='+max,
        success: (reply) => {
            let {...o} = reply;
            let array = [];
            DATA['returnMaster'] = o['value'];
            for (let order of reply['value']) {
                order['name'] = order['signNo'] + '-' + order['employeeNo'];
                order['employee'] = order['employeeNo'];
                order['sign'] = order['signNo'];
                delete order['signNo'];
                delete order['employeeNo'];
                if (order['state'] >= 1) array.push(order);
            }
            returnList.html(datalistgen('return-list', array));
        }
    });
});

$(() => {
    let server = 'http://www.fjemiot.cn/erp/',
        $outSale = $('.outSale-view'),
        $outReturn = $('.outReturn-view');

    let titles = {
            outSale: ['日期', '出仓编号', '销售单号', '运费', '状态', '出货日期', '员工编号', '类型', '分切费', '销售员编号', '客户编号'],
            outReturn: ['日期', '出仓编号', '退货单号', '状态', '签订方', '出货日期', '员工编号', '类型']
        },
        viewMessage = {
            outSale: {
                url: server + 'outStorage',
                title: '销售出仓单',
                view: $outSale,
                table: 'value',
                data: {pageNum: 1, pageSize: 15, type: 0},
                titles: titles.outSale,
                func: (reply) => {
                    $outSale.html('');
                }
            },
            outReturn: {
                url: server + 'outStorage',
                title: '退货出仓单',
                view: $outReturn,
                table: 'value',
                data: {pageNum: 1, pageSize: 15, type: 1},
                titles: titles.outReturn,
                func: (reply) => {
                    $outReturn.html('');
                }
            }
        };

    for (let view in viewMessage) initialize(viewMessage[view]);

    let $rightContain = $('.right-contain'),
        $formArea = $('.form-area');

    //列表选择
    $rightContain.on('click', '.table-show tr', function (e) {
        $('.table-show .select-tr').removeClass('select-tr');
        $(this).addClass('select-tr');
    });
    $formArea.on('click', '.detail-show tr', function (e) {
        $('.detail-show .select-tr').removeClass('select-tr');
        $(this).addClass('select-tr');
    });

    //查看明细
    $rightContain.on('click', 'button.show-outDetail', function (e) {
        let dataLine = $('.right-contain .table-show .select-tr'),
            view = $('.form-area .outDetail-view'),
            order;

        if (dataLine.length == 1) {
            order = dataLine.children().eq(1).text();
            view.parents('.form-box').find('.title span').text(order);
            initializeDetail({
                url: server + 'outStorageDetail',
                title: '出仓明细',
                order: order,
                view: view,
                table: 'value',
                func: (reply) => {
                    view.html('');
                    for (let detail of reply['value']) {
                        delete detail['outStorageNo'];
                        detail['product'] = detail['product']['productNo'] + '-' + detail['product']['brand'] + '-' + detail['product']['type'];
                    }
                },
                titles: ['编号', '数量', '产品']
            });
            $('.form-area .outDetail').removeClass('fade-out hide').addClass('outDetail-slide-down show');
        } else {
            tip.alert('未选中行', '出仓', 'warn');
        }
    });

    //明细增删改
    $formArea.on('click', 'button', function (e) {
        let types = e.target.classList.item(0).split('-');
        if (types[0] == 'add') {
            window.operation = 'add';
            $('.outDetailForm input').each((i, tag) => {
                if (i == 0 || i == 1) $(tag).removeAttr('readonly').css('backgroundColor', '#f7f7f7').css('color', '#aaa');
                $(tag).val('');
            });
            $('.outDetailForm')
                .removeClass('fade-out hide')
                .addClass('outDetailForm-slide-down show')
                .attr('orderNo', $(e.target).parents('.form-box').find('.title span').text());
        } else if (types[0] == 'upd') {
            window.operation = 'upd';
            let dataLine = $('.form-area .detail-show .select-tr');
            if (dataLine.length == 1) {
                let trs = dataLine.children(),
                    inputs = $('.form-area .outDetailForm input');
                inputs.eq(0).val(trs.eq(0).text());
                inputs.eq(1).val(trs.eq(2).text().split('-')[0]);
                inputs.eq(2).val(trs.eq(1).text());
                inputs.eq(0).attr('readonly', 'readonly')
                    .css('backgroundColor', '#aaa').css('color', '#f7f7f7');
                inputs.eq(1).attr('readonly', 'readonly')
                    .css('backgroundColor', '#aaa').css('color', '#f7f7f7');
                $('.form-area .outDetailForm')
                    .removeClass('fade-out hide')
                    .addClass('outDetailForm-slide-down show')
                    .attr('orderNo', $(e.target).parents('.form-box').find('.title span').text());
            } else {
                tip.alert('未选中行', '出仓明细', 'warn');
            }
        }

        $.ajax({
            url: 'http://www.fjemiot.cn/erp/orderDetail/1/10000/' + $('.right-contain .select-tr td').eq(2).text(),
            success: (reply) => {
                let array = [],
                    list = $('.sale-product-list-contain');
                for (let p of reply['value']) {
                    p['product']['name'] = p['product']['brand'] + '-' + p['product']['type'];
                    array.push(p['product']);
                }
                DATA['product'] = array;
                list.html(datalistgen('sale-product-list', array));
            }
        });
    });

    //订单明细增改
    $('.outDetail-submit').click(function () {
        let values = {}, empty = false;
        $(this).parent().find('input').each((i, tag) => {
            let value = tag.value.trim();
            values[tag.getAttribute('name')] = value;
            if (value == '') empty = true;
        });
        if (!empty) {
            let productArray = DATA['product'],
                view = $('.form-area .outDetail-view');
            values['product'] = {};
            values['product']['productNo'] = values['productNo'];
            values['outStorageNo'] = $(this).parent().attr('orderNo');

            for (let p of productArray) {
                if (p['productNo'] == values['productNo']) {
                    values['price'] = p['price'] * values['number'];
                }
            }

            $.ajax({
                url: server + 'outStorageDetail',
                type: window.operation == 'add' ? 'post' : 'put',
                data: JSON.stringify(values),
                dataType: 'json',
                contentType: 'application/json',
                success: (reply) => {
                    let message = window.operation == 'add' ? '添加' : '修改';
                    if (reply == '1001') {
                        tip.alert(message + '成功', '出仓明细', 'success');
                        initializeDetail({
                            url: server + 'outStorageDetail',
                            title: '出仓明细',
                            order: values['outStorageNo'],
                            view: view,
                            table: 'value',
                            func: (reply) => {
                                view.html('');
                                for (let detail of reply['value']) {
                                    delete detail['outStorageNo'];
                                    detail['product'] = detail['product']['productNo'] + '-' + detail['product']['brand'] + '-' + detail['product']['type'];
                                }
                            },
                            titles: ['编号', '数量', '产品']
                        });
                        document.body.click();
                    } else {
                        tip.alert(message + '失败', '出仓明细', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply);
                    tip.alert('已有该产品', '出仓明细', 'error', 5000);
                }
            });
        } else {
            tip.alert('输入不能为空', '出仓明细', 'warn');
        }
    });

    //订单明细删除
    $('.del-outDetail').click(function () {
        let dataLine = $('.form-area .detail-show .select-tr'),
            view = $('.form-area .outDetail-view');
        if (dataLine.length == 1) {
            let orderNo = $(this).parents('.form-box').find('.title span').text(),
                productNo = dataLine.children().eq(2).text().split('-')[0];
            $.ajax({
                url: server + 'outStorageDetail/' + orderNo + '/' + productNo,
                type: 'delete',
                success: (reply) => {
                    if (reply == '1001') {
                        tip.alert('删除成功', '销售明细', 'success');
                        initializeDetail({
                            url: server + 'outStorageDetail',
                            title: '出仓明细',
                            order: orderNo,
                            view: view,
                            table: 'value',
                            func: (reply) => {
                                view.html('');
                                for (let detail of reply['value']) {
                                    delete detail['outStorageNo'];
                                    detail['product'] = detail['product']['productNo'] + '-' + detail['product']['brand'] + '-' + detail['product']['type'];
                                }
                            },
                            titles: ['编号', '数量', '产品']
                        });
                    } else {
                        tip.alert('删除失败', '出仓明细', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply);
                    tip.alert(reply['responseJSON']['message'], '出仓明细', 'error', 5000);
                }
            });
        } else {
            tip.alert('未选中行', '出仓明细', 'warn');
        }
    });

    $('.add-out-s').click(() => {
        window.operation = 'add';
        $('.form-area .outSale .detail').html('');
        $('.form-area .outSale input').each((i, tag) => {
            tag.value = '';
        });
        $('.form-area .outSale').removeClass('fade-out hide').addClass('outSale-slide-down show');
    });
    $('.upd-out-s').click(() => {
        window.operation = 'upd';
        let dataLine = $('.right-contain .table-show .select-tr'),
            outSale = $('.form-area .outSale');
        if (dataLine.length == 1) {
            let datas = dataLine.children(), inputs = outSale.find('.master input');
            outSale.find('.detail').html('');
            inputs.eq(0).val(datas.eq(2).text());
            inputs.eq(1).val(datas.eq(5).text());
            inputs.eq(2).val(datas.eq(6).text());
            outSale.attr('outNo', datas.eq(1).text());
            outSale.removeClass('fade-out hide').addClass('outSale-slide-down show');
        } else {
            tip.alert('未选中行', '出仓', 'warn');
        }
    });
    $('.outSale-submit').click(function () {
        let values = {}, empty = false, detail = [];
        $(this).parent().find('.master input').each((i, tag) => {
            let value = tag.value.trim();
            values[tag.getAttribute('name')] = value;
            if (value == '') empty = true;
        });
        $(this).parent().find('.detail input').each((i, tag) => {
            if (tag != undefined) {
                let value = tag.value.trim(),
                    valueP = {product: {}};
                valueP['product']['productNo'] = value;
                detail.push(valueP);
                if (value == '') empty = true;
            }
        });

        if (!empty) {
            values['type'] = 0;
            values['state'] = 0;
            if (window.operation == 'upd') values['outStorageNo'] = $(this).parents('.form-box').attr('outNo');
            for (let sale of DATA['orderMaster']) {
                if (values['orderNo'] == sale['orderNo']) {
                    values['saleNo'] = sale['employee'];
                    values['customerNo'] = sale['customer'];
                }
            }
            let finalDate = values;
            finalDate['outStorageDetails'] = detail;

            console.log(finalDate)
            $.ajax({
                url: server + 'outStorage',
                type: window.operation == 'add' ? 'post' : 'put',
                data: JSON.stringify(finalDate),
                dataType: 'json',
                contentType: 'application/json',
                success: (reply) => {
                    if (reply == '1001') {
                        tip.alert('成功', '出仓', 'success');
                        for (let view in viewMessage) initialize(viewMessage[view]);
                        document.body.click();
                    } else {
                        tip.alert('失败', '出仓', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply['responseJSON']['message']);
                    tip.alert(reply['responseJSON']['message'], '出仓', 'error', 5000);
                }
            });
        } else {
            tip.alert('输入不能为空', '出仓', 'warn');
        }
    });

    //['日期', '出仓编号', '退货单号', '状态', '签订方', '出货日期', '员工编号', '类型']
    $('.add-out-r').click(() => {
        window.operation = 'add';
        $('.form-area .outReturn .detail').html('');
        $('.form-area .outReturn input').each((i, tag) => {
            tag.value = '';
        });

        $('.form-area .outReturn').removeClass('fade-out hide').addClass('outReturn-slide-down show');
    });
    //['日期', '出仓编号', '退货单号', '状态', '签订方', '出货日期', '员工编号', '类型']
    $('.upd-out-r').click(function() {
        window.operation = 'upd';
        let dataLine = $('.right-contain .table-show .select-tr'),
            outReturn = $('.form-area .outReturn');
        if (dataLine.length == 1) {
            let datas = dataLine.children(), inputs = outReturn.find('.master input');
            outReturn.find('.detail').html('');
            inputs.eq(0).val(datas.eq(2).text());
            inputs.eq(1).val(datas.eq(5).text());
            inputs.eq(2).val(datas.eq(6).text());
            outReturn.attr('outNo', datas.eq(1).text());
            outReturn.removeClass('fade-out hide').addClass('outReturn-slide-down show');
        } else {
            tip.alert('未选中行', '出仓', 'warn');
        }
    });
    $('.outReturn-submit').click(function() {
        let values = {}, empty = false, detail = [];
        $(this).parent().find('.master input').each((i, tag) => {
            let value = tag.value.trim();
            values[tag.getAttribute('name')] = value;
            if (value == '') empty = true;
        });
        $(this).parent().find('.detail input').each((i, tag) => {
            if (tag != undefined) {
                let value = tag.value.trim(),
                    valueP = {product: {}};
                valueP['product']['productNo'] = value;
                detail.push(valueP);
                if (value == '') empty = true;
            }
        });

        if (!empty) {
            let date = new Date();
            values['type'] = 1;
            values['state'] = 0;
            values['date'] = date.getFullYear()+'-'+date.getMonth()+'-'+date.getDate();
            if (window.operation == 'upd') values['outStorageNo'] = $(this).parents('.form-box').attr('outNo');
            for (let return_ of DATA['returnMaster']) {
                if (values['returnNo'] == return_['returnNo']) {
                    values['signNo'] = return_['sign'];
                }
            }
            let finalDate = values;
            finalDate['outStorageDetails'] = detail;

            console.log(finalDate);
            $.ajax({
                url: server + 'outStorage',
                type: window.operation == 'add' ? 'post' : 'put',
                data: JSON.stringify(finalDate),
                dataType: 'json',
                contentType: 'application/json',
                success: (reply) => {
                    if (reply == '1001') {
                        tip.alert('成功', '出仓', 'success');
                        for (let view in viewMessage) initialize(viewMessage[view]);
                        document.body.click();
                    } else {
                        tip.alert('失败', '出仓', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply['responseJSON']['message']);
                    tip.alert(reply['responseJSON']['message'], '出仓', 'error', 5000);
                }
            });
        } else {
            tip.alert('输入不能为空', '出仓', 'warn');
        }
    });
    //审核
    $('.examine-out-s').click(() => {
        window.outType = 0;
        let form = $('.form-area .examine'),
            dataLine = $('.right-contain .select-tr');

        if (dataLine.length == 1) {
            form.find('input').eq(0).val(dataLine.children().eq(1).text());
            form.removeClass('fade-out hide')
                .addClass('examine-slide-down show');
        } else {
            tip.alert('未选中行', '出仓', 'warn');
        }
    });
    $('.examine-out-r').click(() => {
        window.outType = 1;
        let form = $('.form-area .examine'),
            dataLine = $('.right-contain .select-tr');

        if (dataLine.length == 1) {
            form.find('input').eq(0).val(dataLine.children().eq(1).text());
            form.removeClass('fade-out hide')
                .addClass('examine-slide-down show');
        } else {
            tip.alert('未选中行', '出仓', 'warn');
        }
    });
    $('.examine-submit').click(() => {
        let outNo = $('.form-area .examine input').val(),
            state = $('.form-area .examine select').val();

        if (state != 0) {
            $.ajax({
                url: server + 'outStorage',
                type: 'put',
                data: JSON.stringify({outStorageNo:outNo, state:state, type:window.outType}),
                dataType: 'json',
                contentType: 'application/json',
                success: (reply) => {
                    if (reply == '1001') {
                        tip.alert('成功', '出仓', 'success');
                        for (let view in viewMessage) initialize(viewMessage[view]);
                        document.body.click();
                    } else {
                        tip.alert('失败', '出仓', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply['responseJSON']['message']);
                    tip.alert(reply['responseJSON']['message'], '出仓', 'error', 5000);
                }
            });
        } else {
            document.body.click();
        }
    });
    //主表删除
    $('.del-out').click(() => {
        let dataLine = $('.right-contain .table-show .select-tr');
        if (dataLine.length == 1) {
            $.ajax({
                url: server + 'outStorage/' + dataLine.children().eq(1).text(),
                type: 'delete',
                success: (reply) => {
                    if (reply == '1001') {
                        tip.alert('删除成功', '出仓', 'success');
                        for (let view in viewMessage) initialize(viewMessage[view]);
                    } else {
                        tip.alert('删除失败', '出仓', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply);
                    tip.alert(reply['responseJSON']['message'], '出仓', 'error', 5000);
                }
            });
        } else {
            tip.alert('未选中行', '出仓', 'warn');
        }
    });


});

$(() => {
    let $outForm = $('.form-area .outSale'),
        $outReturn = $('.form-area .outReturn'),
        detailHtml = '<label>产品编号</label><input type="number" class="detail-input" placeholder="产品编号" list="sale-product-list">',
        detailHtmlR = '<label>产品编号</label><input type="number" class="detail-input" placeholder="产品编号" list="return-product-list">';
    //add detail form
    $outForm.find('.add-detail').click(() => {
        if (window.operation == 'add') {
            let orderNo = $('.form-area .outSale input').eq(0).val().trim(),
                list = $('.sale-product-list-contain');
            $outForm.find('.detail').append(detailHtml);
            if (orderNo != '') {
                $.ajax({
                    url: 'http://www.fjemiot.cn/erp/orderDetail/1/10000/' + orderNo,
                    success: (reply) => {
                        let array = [];
                        for (let p of reply['value']) {
                            p['product']['name'] = p['product']['brand'] + '-' + p['product']['type'];
                            array.push(p['product']);
                        }
                        list.html(datalistgen('sale-product-list', array));
                    }
                });
            }
        }
    });

    $outReturn.find('.add-detail').click(() => {
        if (window.operation == 'add') {
            let orderNo = $('.form-area .outReturn input').eq(0).val().trim(),
                list = $('.return-product-list-contain');
            $outReturn.find('.detail').append(detailHtmlR);
            if (orderNo != '') {
                $.ajax({
                    url: 'http://www.fjemiot.cn/erp/returnDetail/1/10000/' + orderNo,
                    success: (reply) => {
                        let array = [];
                        for (let p of reply['value']) {
                            p['product']['name'] = p['product']['brand'] + '-' + p['product']['type'];
                            array.push(p['product']);
                        }
                        list.html(datalistgen('return-product-list', array));
                    }
                });
            }
        }
    })
});